class Post < ActiveRecord::Base
  acts_as_taggable
  has_many :events
  has_and_belongs_to_many :geotags
  acts_as_fulltextable [:title, :description, :body]


  def has_events?
    events.count > 0
  end
  
  def duration?
    events.count > 1
  end

  def process
    #find tags
    tags = body.scan(/\A[а-яА-я\s,]*/)[0]          
    tag_with(tags)
    
    #find dates in post
    dates = DateFinder.find(body)          
    dates.each { |date| self.events.create :date => date }

    #find geotags
    tag_name = body.scan(/>([а-яА-я0-9\s,-]*)</)    
    unless tag_name.blank?
      geotag = Geotag.find_or_create(tag_name[0].to_s)
      self.geotags << geotag unless geotag.nil?
      end
  end

  def get_marker
    marker = nil
    self.geotags.each do |geotag|        
        marker = GMarker.new([geotag.latitude, geotag.longitude], :title => self.title, :info_window => "<div class='info_window'><h4>#{self.title}</h4>#{self.body}</div>")
    end
    marker
  end

  def self.get_markers
    markers = []    
    posts = Post.find(:all, :include => "geotags")
    posts.each do |post|
      post.geotags.each do |geotag|        
        markers << GMarker.new([geotag.latitude, geotag.longitude], :title => post.title, :info_window => "<div class='info_window'><h4>#{post.title}</h4>#{post.body}</div>")
      end
    end
    markers 
  end

  def self.get_markers_by_tag(tag)
    markers = []    
    posts = Post.find_tagged_with(tag) 
    posts.each do |post|
      post.geotags.each do |geotag|        
        markers << GMarker.new([geotag.latitude, geotag.longitude], :title => post.title, :info_window => "<div class='info_window'><h4>#{post.title}</h4>#{post.body}</div>")
      end
    end
    markers 
  end
  

  def self.update_geotags
    posts = Post.find(:all)
    posts.each do |post|
      tag_name = post.body.scan(/>([а-яА-я0-9\s,-]*)</)    
      unless tag_name.blank?
        geotag = Geotag.find_or_create(tag_name[0].to_s)
        post.geotags << geotag unless geotag.nil?
      end      
    end
  end
  
  def self.reload_events
    posts = Post.find(:all)
    posts.each do |post|
      dates = DateFinder.find(post.body)
      dates.each { |date| post.events.create :date => date }
    end
  end  
end
